import React from 'react';
import { Tabs, Form, Input, Button } from 'antd';
import { LockBlack, UserBlack, LoadingBlack } from '@/components/el/ElIcon';
import { observer, inject } from 'mobx-react';
import * as service from './service';
import './style.less';
import { ElNotification } from '@/components/el';
import { enCodeStr } from '@/utils/utils';

const { TabPane } = Tabs;

interface State {
  loading: boolean;
  captchaLoading: boolean;
  isShow: boolean;
  answer: string;
  captcha: { [props: string]: any };
  redirectUrl: string;
  openEnvironmentDesc: boolean;
  environmentDesc: string;
}

@inject('store')
@observer
class Login extends React.Component<{ [props: string]: any }, State> {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      captchaLoading: false,
      captcha: {},
      isShow: true,
      answer: '',
      redirectUrl: '',
      openEnvironmentDesc: true,
      environmentDesc: ''
    };
  }

  componentDidMount() {
    localStorage.removeItem('Authorization');
    this.getCaptcha();
    this.getRedirectUrl();
    this.initEnvironment();
  }
  initEnvironment = () => {
    const href = window.location.href;
    if (href.indexOf('nrp-dev') > -1) {
      this.setState({
        environmentDesc: '开发环境'
      });
    }
    if (href.indexOf('nrp-test') > -1) {
      this.setState({
        environmentDesc: '测试环境'
      });
    }
    if (href.indexOf('nrp-uat') > -1) {
      this.setState({
        environmentDesc: 'Uat环境'
      });
    }
    if (href.indexOf('localhost') > -1) {
      this.setState({
        environmentDesc: '本地环境'
      });
    }
  };
  getRedirectUrl = () => {
    if (window.location.search && window.location.search.indexOf('=') > -1) {
      const redirectUrl = window.location.search.split('=')[1];
      this.setState({
        redirectUrl
      });
    }
  };
  //调用接口
  getCaptcha = async () => {
    this.setState({ captchaLoading: true });
    const res: any = await service.getCaptcha();
    if (res.success) {
      this.setState({ captcha: res.data });
    } else {
      ElNotification({
        type: 'error',
        message: res.msg
      });
    }
    this.setState({ captchaLoading: false });
  };
  login = async (params) => {
    this.setState({ loading: true });
    const res: any = await service.login({
      ...params,
      capuid: this.state.captcha.uuid
    });
    this.setState({ loading: false });
    if (res.success) {
      // 浏览器本地缓存token
      localStorage.setItem(
        'Authorization',
        `${res.data.token_type} ${res.data.access_token}`
      );

      // 全局数据栈缓存用户信息
      const userRes = await service.getCurrent();

      if (userRes.success) {
        const orgRes = await service.getOrgInfo();
        if (orgRes.success) {
          this.props.store.updatePrincipal({
            ...userRes.data,
            buData: orgRes.data
          });
        }
      }
      const redirectUrl = this.state.redirectUrl;
      this.setState({
        redirectUrl: ''
      });
      // 跳转至首页
      this.props.history.push(redirectUrl ? redirectUrl : '/dashboard', {
        replace: true
      });
    } else {
      // 重新获取验证码
      this.getCaptcha();
      ElNotification({
        type: 'error',
        message: res.msg
      });
    }
  };

  // 页面交互事件处理
  handleRefreshCaptcha = () => {
    this.getCaptcha();
  };
  handleLogin = (values) => {
    values.password = enCodeStr(values.password);
    values.terminal = 'BACKEND';
    this.login(values);
  };
  handleValidateFail = ({ errorFields }) => {
    ElNotification({
      type: 'error',
      message: errorFields[0].errors[0]
    });
  };

  render() {
    return (
      <div className={'container'}>
        <div className={'content'}>
          <i className={'logo'} />

          <i className={'img'}>
            <span style={{ fontSize: '80px', color: 'red' }}>
              {this.state.environmentDesc}
            </span>
          </i>

          <Tabs className={'tabs'} tabBarGutter={72}>
            <TabPane tab='账号密码登录' key='1'>
              <Form
                className={'form'}
                onFinish={this.handleLogin}
                onFinishFailed={this.handleValidateFail}
                initialValues={{
                  username: '',
                  password: ''
                }}
              >
                <Form.Item
                  name='username'
                  required
                  rules={[{ required: true, message: '请输入账户名' }]}
                >
                  <Input
                    prefix={<UserBlack className={'icon'} />}
                    className={'input'}
                    placeholder='账户名'
                    autoComplete='off'
                  />
                </Form.Item>
                <Form.Item
                  name='password'
                  required
                  rules={[{ required: true, message: '请输入密码' }]}
                >
                  <Input.Password
                    prefix={<LockBlack className={'icon'} />}
                    className={'input'}
                    placeholder='密码'
                    autoComplete='off'
                  />
                </Form.Item>
                <Form.Item
                  name='captcha'
                  required
                  rules={[{ required: true, message: '请输入验证码' }]}
                >
                  <Input
                    className={'captchaInput'}
                    placeholder='验证码'
                    autoComplete='off'
                    addonAfter={
                      <div
                        onClick={this.handleRefreshCaptcha}
                        style={{ width: 80 }}
                      >
                        {this.state.captchaLoading ? (
                          <LoadingBlack />
                        ) : (
                          <img
                            src={this.state.captcha && this.state.captcha.img}
                            alt='captcha'
                            className={'captcha'}
                          />
                        )}
                      </div>
                    }
                  />
                </Form.Item>
                {/* <Form.Item>
                  <Form.Item name='remember' valuePropName='checked' noStyle>
                    <Checkbox disabled={true} className={'checkbox'}>
                      自动登录
                    </Checkbox>
                  </Form.Item>
                  <a
                    style={{ opacity: 0.2 }}
                    className={'forget'}
                    href='javascript:return false;'
                  >
                    忘记密码？
                  </a>
                </Form.Item> */}
                <Form.Item>
                  <Button
                    type='primary'
                    htmlType='submit'
                    className={'input'}
                    loading={this.state.loading}
                  >
                    登录
                  </Button>
                  {this.state.isShow ? (
                    <div id='answer'>{this.state.captcha.captext}</div>
                  ) : null}
                </Form.Item>
              </Form>
            </TabPane>
            {/* <TabPane tab='手机号登录' key='2' /> */}
          </Tabs>
          <span className={'footer'}>
            Copyright© 2021 云时通产品研发技术部出品{' '}
            <a href='https://beian.miit.gov.cn/#/Integrated/recordQuery'>
              沪ICP备18031690号-1
            </a>
          </span>
        </div>
      </div>
    );
  }
}
export default Login;
